package com.smile.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import feign.codec.Decoder;
import feign.jackson.JacksonDecoder;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.TimeZone;

@Configuration
public class JacksonDateTimeConfig {

    // 定义全局日期时间格式
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final DateTimeFormatter DATE_TIME_FORMATTER =
            DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);

    @Bean
    public HttpMessageConverters customConverters() {
        return new HttpMessageConverters(new MappingJackson2HttpMessageConverter(customObjectMapper()));
    }

    @Bean
    public ObjectMapper customObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // 注册 Java Time 模块
        JavaTimeModule timeModule = new JavaTimeModule();

        // 配置 LocalDateTime 的处理
        timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
        timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME_FORMATTER));

        // 配置 java.util.Date 的处理（使用线程安全的 DateTimeFormatter）
        timeModule.addSerializer(java.util.Date.class, new SafeDateSerializer());
        timeModule.addDeserializer(java.util.Date.class, new SafeDateDeserializer());

        objectMapper.registerModule(timeModule);

        // 处理其他日期类型
        SimpleModule otherDateModule = new SimpleModule();
        otherDateModule.addSerializer(java.sql.Timestamp.class, new SafeSqlTimestampSerializer());
        otherDateModule.addSerializer(java.sql.Date.class, new SafeSqlDateSerializer());
        objectMapper.registerModule(otherDateModule);

        // 解决时区问题
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        // 设置日期格式而不是时间戳
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        return objectMapper;
    }

    /**
     * 线程安全的 java.util.Date 序列化器
     */
    public static class SafeDateSerializer extends JsonSerializer<java.util.Date> {
        @Override
        public void serialize(java.util.Date value, JsonGenerator gen, SerializerProvider provider)
                throws IOException {
            // 使用线程安全的 DateTimeFormatter 进行转换
            String formatted = DATE_TIME_FORMATTER.format(value.toInstant().atZone(java.time.ZoneId.systemDefault()));
            gen.writeString(formatted);
        }
    }

    /**
     * 线程安全的 java.util.Date 反序列化器
     */
    public static class SafeDateDeserializer extends JsonDeserializer<java.util.Date> {
        @Override
        public java.util.Date deserialize(JsonParser p, DeserializationContext ctxt)
                throws IOException {
            String dateStr = p.getText();
            // 使用线程安全的 DateTimeFormatter 进行解析
            LocalDateTime localDateTime = LocalDateTime.parse(dateStr, DATE_TIME_FORMATTER);
            return java.util.Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
        }
    }

    /**
     * 线程安全的 java.sql.Timestamp 序列化器
     */
    public static class SafeSqlTimestampSerializer extends JsonSerializer<java.sql.Timestamp> {
        @Override
        public void serialize(java.sql.Timestamp value, JsonGenerator gen, SerializerProvider provider)
                throws IOException {
            // 使用线程安全的 DateTimeFormatter 进行转换
            String formatted = DATE_TIME_FORMATTER.format(value.toLocalDateTime());
            gen.writeString(formatted);
        }
    }

    /**
     * 线程安全的 java.sql.Date 序列化器
     */
    public static class SafeSqlDateSerializer extends JsonSerializer<java.sql.Date> {
        @Override
        public void serialize(java.sql.Date value, JsonGenerator gen, SerializerProvider provider)
                throws IOException {
            // 使用线程安全的 DateTimeFormatter 进行转换（只包含日期部分）
            String formatted = DATE_TIME_FORMATTER.format(value.toLocalDate().atStartOfDay());
            gen.writeString(formatted.substring(0, 10)); // 只输出日期部分 yyyy-MM-dd
        }
    }

    // 1. 定义 FLEXIBLE_DATETIME_FORMATTER（修复第一个飘红）
    // 1. 定义 FLEXIBLE_DATETIME_FORMATTER（修复第一个飘红）
    public static final DateTimeFormatter FLEXIBLE_DATETIME_FORMATTER = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd[['T'][ ]]HH:mm:ss") // 支持空格和'T'
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter();

//    @Bean
//    public Decoder feignDecoder() {
//        ObjectMapper mapper = new ObjectMapper();
//
//        SimpleModule module = new SimpleModule();
//
//        // 支持灵活的日期时间格式反序列化
//        // 使用上面定义的FLEXIBLE_DATETIME_FORMATTER（现在已定义）
//        module.addDeserializer(LocalDateTime.class,
//                new FlexibleLocalDateTimeDeserializer(FLEXIBLE_DATETIME_FORMATTER));
//
//        // 自定义序列化器（可选）
//        // 修复第二个飘红：将模式字符串补全
//        module.addSerializer(LocalDateTime.class,
//                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//
//        mapper.registerModule(module);
//        return new JacksonDecoder(mapper);
//    }

}
